import Axios from 'axios'
import shajs from 'sha.js'
import _ from 'lodash'

export default {
	/**
	 * @description 用户登录 默认使用 root@admin.com 登录
	 * @param username 名称
	 * @param password 密码
	 */
	login: (
		{ username, password } = { username: 'root@admin.com', password: '123456' }
	) => {
		password = shajs('sha256')
			.update(password)
			.digest('hex')
		return Axios.post('/frame/login', { username, password }).then(res => {
			window.localStorage.setItem('token', res.data.token)
			return res.data
		})
	},

	/**
	 * @description 退出登录
	 */
	logout: () => Axios.post('/frame/logout').then(res => res.data),

	/**
	 * @description 获取用户简单列表
	 */
	userSimpleList: () => Axios.get('/users/simple').then(res => res.data),

	/**
	 * @description 获取用户列表
	 * @param query 查询参数
	 */
	userList: query =>
		Axios.get('/users', { params: query }).then(res => res.data),

	/**
	 * @description 删除用户
	 * @param id 用户ID
	 */
	deleteUser: id => Axios.delete('/users/' + id).then(res => res.data),

	/**
	 * @description 新增用户
	 * @param user 用户信息
	 */
	addUser: user => {
		const clone = _.cloneDeep(user)
		clone.password = shajs('sha256')
			.update(clone.password)
			.digest('hex')
		return Axios.post('/users', clone).then(res => res.data)
	},

	/**
	 * @description 编辑用户
	 * @param user 用户信息
	 */
	updateUser: user => {
		const clone = _.cloneDeep(user)

		if (clone.newPassword) {
			clone.newPassword = shajs('sha256')
				.update(clone.newPassword)
				.digest('hex')
		}

		if (clone.oldPassword) {
			clone.oldPassword = shajs('sha256')
				.update(clone.oldPassword)
				.digest('hex')
		}

		console.log(user == clone)

		return Axios.put('/users', clone).then(res => res.data)
	},

	/**
	 * @description 获取用户详细信息
	 * @param id 用户ID
	 */
	getUserInfo: id => Axios.get(`/users/${id}`).then(res => res.data),

	/**
	 * @description 获取权限列表
	 * @param query 查询参数
	 */
	permissions: query => {
		return Axios.get('/permissions', {
			params: query
		})
	},

	// 权限组删除
	permissionsDelete: id => {
		console.log(id)
		return Axios.delete('/permissions/' + id)
	},

	// 得到树形列表的数据
	permissionsOK: () => {
		return Axios.get('/menus')
	},

	// 得到具体权限组数据
	permissionsInfo: id => {
		return Axios.get(`/permissions/${id}`)
	},

	// 添加权限组
	permissionsAdd: dataAdd => {
		return Axios.post('/permissions', dataAdd)
	},

	/**
	 * @description 编辑权限组
	 */
	permissionsEdit: editData => {
		console.log(editData)
		return Axios.put(`/permissions/${editData.id}`, editData)
	},
	/**
	 * @description 用户简单列表
	 */
	permissionGroupSimpleList: params =>
		Axios.get('/permissions/simple', { params }).then(res => res.data)
}
